/*************************************************************************
  Crytek Source File.
  Copyright (C), Crytek Studios, 2001-2010.
 -------------------------------------------------------------------------
  $Id$
  $DateTime$
  
 -------------------------------------------------------------------------
  History:
  - Oct 27th, 2010  : Created by Michelle Martin
 *************************************************************************/

#include "StdAfx.h"
#include "IKTarget_AttachedHelperPos.h"
#include <IEntitySystem.h>  // for GetEntity() by id




CIKTarget_AttachedHelperPos::CIKTarget_AttachedHelperPos(const SIKTargetParams& ikParams, QuatT &startPosition, EntityId targetEntityID, const char* attachmentName) : CIKTarget_Base(ikParams, startPosition)
{
	m_targetEntity = gEnv->pEntitySystem->GetEntity(targetEntityID);
	if (!m_targetEntity)
		CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_ERROR, "IK Target: Invalid Entity ID for Attachment Target, this will cause the IK to crash when used with this");
	m_attachmentName = attachmentName;
	if (m_attachmentName.empty())
		CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_ERROR, "IK Target: No Helper Name specified - this won't work with the IK when this target is used.");
}

QuatT CIKTarget_AttachedHelperPos::UpdateWorldPos( float frameTime )
{
	CRY_ASSERT_MESSAGE(m_targetEntity, "IK Target: Target Entity invalid, this will cause a crash.");
	CRY_ASSERT_MESSAGE(!m_attachmentName.empty(), "IK Target: Helper Name empty, this will case the IK Target Point to be at the wrong location.");
	
	return GetHelperPosFromEntityObject(m_targetEntity, m_attachmentName.c_str());
}



// ===========================================================================
// ===========================================================================

const QuatT CIKTarget_AttachedHelperPos::GetHelperPosFromEntityObject( IEntity* pEntity, const char* helperName )
{
	QuatT loc(IDENTITY);
	int slotCount = pEntity->GetSlotCount();
	for (int i = 0; i < slotCount; i++)
	{
		// check if there is a static object in this slot
		IStatObj *pObj = pEntity->GetStatObj(i);
		if (!pObj)
			continue;

		if (pObj->GetGeoName() != NULL)
		{
			_smart_ptr<IStatObj> pRootObj = gEnv->p3DEngine->LoadStatObj(pObj->GetFilePath());
			if (pRootObj)
				loc = QuatT(pRootObj->GetHelperTM(helperName));
		}
		else
		{
			loc = QuatT(pObj->GetHelperTM(helperName));
		}

		SEntitySlotInfo slotInfo;
		pEntity->GetSlotInfo(i, slotInfo);
		if (slotInfo.nParentSlot != -1)
		{
			loc = QuatT(pEntity->GetSlotLocalTM(i, true)) * loc;
		}

		// if the helper was found, transform it into world space
		if (!loc.IsIdentity())
		{
			loc = QuatT(pEntity->GetSlotWorldTM(i)) * loc;
			break;
		}

	}

	return loc;
}





